<template>
    <div class="agency-detail">
        <a-modal width="1300px" :visible="visible" title="机构详情" @cancel="closeModal" class="yuan-modal agency-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :class="isShow?'disable-form':''" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel yuan-form-col3">
                        <div class="form-panel-box">
                            <div class="form-title">机构信息</div>

                            <a-form-model-item class="yuan-form-item" label="机构名称" prop="name">
                                <a-input class="yuan-form-input" placeholder="机构名称" v-model="formData.name"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="机构类型" prop="institutionalType">
                                <a-select class="yuan-form-input" v-model="formData.institutionalType" allowClear
                                    placeholder="机构类型">
                                    <a-select-option value="中医馆">中医馆</a-select-option>
                                    <a-select-option value="体检中心">体检中心</a-select-option>
                                    <a-select-option value="社区医院">社区医院</a-select-option>
                                    <a-select-option value="养老中心">养老中心</a-select-option>
                                    <a-select-option value="口腔门诊">口腔门诊</a-select-option>
                                </a-select>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="自营/加盟" prop="storeType">
                                <a-radio-group class="yuan-form-input" v-model="formData.storeType">
                                    <a-radio value="ZY">自营</a-radio>
                                    <a-radio value="JM">加盟</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="手机号" prop="phone">
                                <a-input class="yuan-form-input" v-model="formData.phone" placeholder="请输入手机号"
                                    autocomplete="new-user"></a-input>
                            </a-form-model-item>

                            <template v-if="!formData.id">
                                <a-form-model-item class="yuan-form-item" label="账号" prop="account">
                                    <a-input class="yuan-form-input" v-model="formData.account" placeholder="请输入账号"
                                        autocomplete="new-user"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item" label="密码" prop="password">
                                    <a-input class="yuan-form-input" v-model="formData.password" type="password"
                                        placeholder="请输入密码" autocomplete="new-password"></a-input>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-item" label="二次确认" prop="surePassword">
                                    <a-input class="yuan-form-input" v-model="formData.surePassword" type="password"
                                        placeholder="请再次输入密码"></a-input>

                                </a-form-model-item>
                            </template>
                            <template v-else>
                                <a-form-model-item class="yuan-form-item" label="账号" prop="account">
                                    <span class="yuan-form-input">{{formData.account}}</span>
                                </a-form-model-item>

                            </template>

                            <a-form-model-item class="yuan-form-item" label="医馆规模(人)" prop="hospitalScale">
                                <a-input class="yuan-form-input" type="number" placeholder="医馆规模"
                                    v-model="formData.hospitalScale"></a-input>
                            </a-form-model-item>

                            <a-form-model-item label="营业执照" class="yuan-form-row" v-if="pageReady" prop="businessLicense">
                                <UploadVue :uploadLength="1" @uploadChange="uploadChangeBusinessLicense"
                                    :defImgList="formData.businessLicense?[formData.businessLicense]:[]" />
                                <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                            </a-form-model-item>

                            <a-form-model-item label="医馆图片" class="yuan-form-row" v-if="pageReady" prop="hospitalPicture">
                                <UploadVue :uploadLength="6" @uploadChange="uploadChangeCoverImageUrl"
                                    :defImgList="formData.hospitalPicture.length>0?formData.hospitalPicture:[]" />
                                <div style="line-height:30px">jpg.png.gif格式.不超过2MB，最多6张</div>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="医馆特色" prop="hospitalFeature">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.hospitalFeature" placeholder="请输入医馆特色" :maxLength="500" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="医馆地址" prop="hospitalSite">
                                <a-input class="yuan-form-input" style="max-width:350px" placeholder="医馆地址"
                                    v-model="formData.hospitalSite"></a-input>
                                <a-button type="primary" style="margin-left:20px" @click="getGeocode">获取定位</a-button>
                            </a-form-model-item>
                            <div id="myMap"></div>
                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <template v-if="isShow">
                    <a-button @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="modalOk" type="primary" :loading="saveLoading">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>

            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import { mapLoad } from "@/utils";
import axios from "axios";
import platformApi from "@/api/platformApi";
let carWorkLogMap: any = null;
@Component({
    name: "tpl",
    components: { UploadVue },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editInfo!: any;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            if (this.editInfo.id) {
                this.formData = { ...this.editInfo, hospitalPicture: this.editInfo.hospitalPicture || [] };
                this.pageReady = true;
            } else {
                this.formData = {
                    phone: "",
                    hospitalSite: "",
                    hospitalPicture: [],
                };
                this.pageReady = true;
            }
            this.$nextTick(() => {
                this.mapInit();
            });
        } else {
            this.pageReady = false;
        }
    }
    saveLoading = false;
    formData: any = {
        phone: "",
        hospitalSite: "",
        hospitalPicture: [],
    };
    rules = {
        name: [{ required: true, message: "请输入机构名称", trigger: "change" }],
        institutionalType: [{ required: true, message: "请选择机构类型", trigger: "change" }],
        storeType: [{ required: true, message: "请选择自营/加盟", trigger: "change" }],
        phone: [{ required: true, message: "请输入机构手机号", trigger: "change" }],
        account: [{ required: true, message: "请输入机构账号", trigger: "change" }],
        password: [{ required: true, message: "请输入机构账号密码", trigger: "change" }],
        surePassword: [{ required: true, message: "请重复机构账号密码", trigger: "change" }],
        hospitalScale: [{ required: true, message: "请输入医馆规模", trigger: "change" }],
        businessLicense: [{ required: true, message: "请上传营业执照", trigger: "change" }],
        hospitalPicture: [{ required: true, message: "请上传医馆图片", trigger: "change" }],
        hospitalFeature: [{ required: true, message: "请属于医馆特色", trigger: "change" }],
        hospitalSite: [{ required: true, message: "请填写医馆地址", trigger: "change" }],
    };
    pageReady = false;

    editAddress(lnglat, address) {
        this.formData.addressCode = lnglat;
        this.formData.hospitalSite = address;
    }
    async mounted() {}

    beforeDestroy() {
        carWorkLogMap = null;
    }

    mapInit() {
        mapLoad(() => {
            if (carWorkLogMap) {
                carWorkLogMap.clearMap();
                carWorkLogMap.setZoom(11);
            } else {
                carWorkLogMap = new AMap.Map("myMap", {
                    zoom: 11,
                    center: [104.065861, 30.657401],
                });
            }

            carWorkLogMap.on("click", (e) => {
                const lnglat = e.lnglat;
                // 逆地理编码
                AMap.plugin("AMap.Geocoder", () => {
                    const geocoder = new AMap.Geocoder();
                    geocoder.getAddress(lnglat, (status, result) => {
                        if (status === "complete" && result.regeocode) {
                            const address = result.regeocode.formattedAddress;
                            carWorkLogMap.clearMap();
                            // 添加标记
                            new AMap.Marker({
                                map: carWorkLogMap,
                                position: lnglat,
                            });

                            carWorkLogMap.setCenter(lnglat);
                            carWorkLogMap.setZoom(18);
                            this.editAddress(lnglat.lng + "," + lnglat.lat, address);
                        } else {
                            console.info(result);
                        }
                    });
                });
            });

            if (this.editInfo.id && this.editInfo.siteCoordinate.latitude) {
                const location = [this.editInfo.siteCoordinate.longitude, this.editInfo.siteCoordinate.latitude]; // 格式："经度,纬度"
                carWorkLogMap.clearMap();
                let marker = new AMap.Marker({
                    map: carWorkLogMap,
                    position: location,
                });

                carWorkLogMap.setCenter(location);
                carWorkLogMap.setZoom(18);
                this.formData.addressCode = location.join(",");
            }
        });
    }
    closeModal() {
        this.$emit("closeModal");
    }

    async modalOk() {
        if (!this.formData.id) {
            if (this.formData.password !== this.formData.surePassword) {
                this.$message.error("新密码和重复密码不一致，请检查后重试");
                return;
            }
        }

        if (!this.formData.addressCode) {
            this.$message.error("请点击获取定位按钮获取医馆地址坐标");
            return;
        }

        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const codeArr = this.formData.addressCode.split(",");
                const res = await platformApi.addOrganization({
                    ...this.formData,
                    siteCoordinate: {
                        longitude: codeArr[0],
                        latitude: codeArr[1],
                    },
                });
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }
    async getGeocode() {
        if (!this.formData.hospitalSite) {
            this.$message.error("请先填写医馆地址或直接在地图选中");
            return;
        }
        const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(
            this.formData.hospitalSite
        )}&key=71c1920025ff6d7d00100187f0bb98d3`;
        try {
            const response = await axios.get(url);
            if (response.data.status === "1" && response.data.geocodes.length > 0) {
                const location = response.data.geocodes[0].location; // 格式："经度,纬度"
                carWorkLogMap.clearMap();
                let marker = new AMap.Marker({
                    map: carWorkLogMap,
                    position: location.split(","),
                });

                carWorkLogMap.setCenter(location.split(","));
                carWorkLogMap.setZoom(18);
                this.formData.addressCode = location;
            } else {
                this.$message.error('地址解析失败')
                throw new Error("地址解析失败: " + response.data.info);
            }
        } catch (error: any) {
            console.error("API请求错误:", error.message);
            return null;
        }
    }

    uploadChangeCoverImageUrl(e) {
        this.formData.hospitalPicture = e.length ? e.map((item) => item.url) : [];
    }
    uploadChangeBusinessLicense(e) {
        this.formData.businessLicense = e.length ? e[0].url : "";
    }
}
</script>
<style lang="scss">
.agency-detail-modal {
    #myMap {
        width: 100%;
        height: 300px;
    }
}
</style>
